<?php


namespace app\api\model;


use app\api\help\Http;
use app\common\model\TimeModel;
use think\facade\Db;

class MallWxapp extends TimeModel
{
    /**
     * 获取access_token
     */
    public static function getAccessToken()
    {
        $where = [['wxapp_id', '=', 10001]];
        $wechat = Db::name('mall_wxapp')->where($where)->find();
        if (!empty($wechat)) {
            if ($wechat['expire_time'] - time() < (7200 - 300)) {
                //access_token失效,重新获取access_token
                $res = self::initAccessToken($wechat);
                if (!empty($res) && !isset($res['errcode'])) {
                    $data = [
                        'access_token' => $res['access_token'],
                        'expire_time' => time() + $res['expires_in']
                    ];
                    if (false !== Db::name('mall_wxapp')->where($where)->update($data)) {
                        return $res['access_token'];
                    } else {
                        _outPut(204);
                    }
                } else {
                    // 获取access_token失败
                    _outPut(601, $res, 'wechat get access_token error');
                }
            } else {
                return $wechat['access_token'];
            }
        } else {
            _outPut(602, 'wechat_id is not exist');
        }
    }
    /**
     * 获取access_token
     */
    public static function initAccessToken($param)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$param['app_id']}&secret={$param['app_secret']}";
        $res = Http::request($url);
        $res = json_decode($res, true);
        return $res;
    }
}